#include"MyPlayer.h"
int TryGetVideoCodec(FF_VIDEOINFO*videoinfo,AVFormatContext *fmt_ctx){
    videoinfo->idx=FindVideoCodec(fmt_ctx);
    if(videoinfo->idx!=-1){
       AVCodec *dec = NULL;
       videoinfo->stream=fmt_ctx->streams[videoinfo->idx];
       videoinfo->codec=videoinfo->stream->codec;
       dec=avcodec_find_decoder(videoinfo->codec->codec_id);
       if(dec==NULL){
          printf("Find Video dec failed %s\n",avcodec_get_name(videoinfo->codec->codec_id)); 
		  return -1;
       }
       if(avcodec_open2(videoinfo->codec,dec,NULL)<0){
		  printf("Open Video dec failed %s\n",avcodec_get_name(videoinfo->codec->codec_id)); 
		  return -1;
	   }else{
          //videoinfo->length = av_image_get_buffer_size(VIDEO_TYPE,WINDOWS_WIDTH,WINDOWS_HIGHT,1);
#if USE_FFMPEG_SWS
          videoinfo->length = avpicture_get_size(VIDEO_TYPE,WINDOWS_WIDTH,WINDOWS_HIGHT);
	      videoinfo->pSws = sws_getCachedContext(videoinfo->pSws, 
          videoinfo->codec->width,videoinfo->codec->height,videoinfo->codec->pix_fmt,
          WINDOWS_WIDTH,WINDOWS_HIGHT,VIDEO_TYPE,
          SWS_BICUBIC,NULL, NULL, NULL);
#endif
       }
    }
    return  videoinfo->idx;
}

int TryDecVideoPacket(FF_VIDEOINFO*videoinfo,AVPacket*packet,AVFrame*pFrame){  
	int frameFinished=0;	
	avcodec_decode_video2(videoinfo->codec,pFrame,&frameFinished,packet);
	printf("got_frame:%d packet_pts:%lld frame_pts:%I64d\n", frameFinished, packet->pts, pFrame->pts);
    if(frameFinished){    
       pFrame->pts = av_frame_get_best_effort_timestamp(pFrame);
       if (pFrame->pts != AV_NOPTS_VALUE) {
		   double pts=av_q2d(videoinfo->stream->time_base)*pFrame->pts;		   
#if USE_FFMPEG_SWS		    
		    uint8_t*buffer = (uint8_t *)av_mallocz(videoinfo->length);
		    AVPicture pPicture = { { NULL },{ 0 } };
            avpicture_fill(&pPicture,buffer,VIDEO_TYPE,WINDOWS_WIDTH,WINDOWS_HIGHT);
            sws_scale(videoinfo->pSws,(const uint8_t*const*)pFrame->data,pFrame->linesize,0,videoinfo->codec->height, 
            pPicture.data,pPicture.linesize);
            PushVideoPacket(buffer,WINDOWS_WIDTH,WINDOWS_HIGHT,pts*1000);
#else
		    uint8_t*buffer = (uint8_t *)av_mallocz(pFrame->width*pFrame->height*3/2);
			int i = 0,j=0;
			uint8_t*pos = buffer;
			for (i = 0; i<3; i++) {
				int shift = i>0 ? 1 : 0;
				char*yuv = pFrame->data[i];
				for (j = 0; j<(pFrame->height >> shift); j++) {
					memcpy(pos, yuv, pFrame->width >> shift);
					pos += (pFrame->width >> shift);
					yuv += pFrame->linesize[i];
				}
			}
		    PushVideoPacket(buffer,pFrame->width,pFrame->height,pts*1000);
#endif
			printf("pFrame->pts:%I64d %f %d x %d\n",pFrame->pts,pts,pFrame->width,pFrame->height);
       }
	   
       while(GetVideoPacketLength()>10){
          SDL_Delay(100);
       }
    }
    return 0;
}